<template>
  <div class="form-item">
    <p class="form-item__label form-item__required">指标体系：</p>
    <a-select
      class="form-item__content"
      v-model:value="currentIndicatorSystem"
      :options="indicatorSystemOptions"
      :field-names="{ label: 'label', value: 'id', options: 'children' }"
      @change="handleIndicatorSystemChange"
    ></a-select>
  </div>
  <template v-if="currentIndicatorSystem">
    <a-button
      type="primary"
      class="recommend-button"
      :loading="recommendButtonLoading"
      @click="handleRecommendClick"
      >智能推荐</a-button
    >
    <div class="total-score">总分：{{ total }}分</div>
    <a-table
      v-if="dataSource"
      class="table"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="false"
      :scroll="{
        scrollToFirstRowOnChange: true,
        x: '100%',
      }"
      rowKey="id"
      defaultExpandAllRows
      :sticky="true"
      @resizeColumn="
        (w:number, col: ColumnItem) => {
          col.width = Math.max(w,col.minWidth||0);
        }
      "
    >
      <template #bodyCell="{ column, record }">
        <template
          v-if="
            column.dataIndex === 'action' &&
            record.nodeType === 1 &&
            [IndicatorTypeEnum.Option, IndicatorTypeEnum.Innovation].includes(
              record.type
            )
          "
        >
          <a-button type="link">替换</a-button>
        </template>
        <template
          v-else-if="
            column.dataIndex === 'canApproval' && record.nodeType === 1
          "
        >
          <a-select
            v-if="
              [IndicatorTypeEnum.Option, IndicatorTypeEnum.Innovation].includes(
                record.type
              )
            "
            style="width: 100%"
            v-model:value="record.canApproval"
            :options="[
              { label: '参与评分', value: true },
              { label: '不参与评分', value: false },
            ]"
          ></a-select>
          <span v-else></span>
        </template>
        <a
          v-else-if="column.dataIndex === 'name' && record.nodeType === 1"
          :href="`/file/indicator/${record.id.replace(
            'I-',
            ''
          )}/indicator.html`"
          target="_blank"
          :title="record[column.dataIndex]"
          :class="{
            highlight: recommendIndicators[record.id.replace('I-', '')],
          }"
        >
          {{
            column.customRender?.({ text: record[column.dataIndex] }) ||
            record[column.dataIndex]
          }}</a
        >
      </template>
    </a-table>
    <a-button
      type="primary"
      :disabled="!currentIndicatorSystem"
      @click="handleSubmitClick"
      >提交</a-button
    >
  </template>
</template>
<script lang="ts" setup>
import { IndicatorTypeEnum } from "@/utils";
import { getCurrentInstance, ref } from "vue";
import {
  IndicatorSystemItem,
  IndicatorSystemDetailItem,
  getIndicatorSystemOptions,
  getIndicatorSystemDetailById,
  saveProjectIndicatorSystem,
  getProjectIndicatorsById,
  getRecommendIndicatorSystem,
} from "@/api";
import { useRoute, useRouter } from "vue-router";
import { getIndicatorColumns } from "../config";
// import Modal from "ant-design-vue/es/modal";
// import ReplaceModal from "./ReplaceModal.vue";
import { message } from "ant-design-vue";
const props = defineProps<{ readOnly: boolean; routeNamePrefix: string }>();
const currentIndicatorSystem = ref<number>();
const indicatorSystemOptions = ref<IndicatorSystemItem[]>([]);
const columns = ref(getIndicatorColumns());
const dataSource = ref<IndicatorSystemDetailItem[]>();
const total = ref(100);
const recommendIndicators = ref<Record<string, any>>({});
const route = useRoute();
const router = useRouter();
const { $loading } =
  getCurrentInstance()?.appContext?.config.globalProperties || {};
getIndicatorSystemOptions()
  .then((res) => {
    indicatorSystemOptions.value = res.map((item) => ({
      ...item,
      label: item.name + item.version,
    }));
  })
  .catch(console.error);
if (route.params.id) {
  getProjectIndicatorsById(Number(route.params.id)).then((res) => {
    currentIndicatorSystem.value = res.systemId;
    if (res.indicators?.length) dataSource.value = res.indicators;
    if (res.status !== +route.params.status) {
      router.replace({
        name: route.name || "",
        params: {
          ...route.params,
          status: res.status,
        },
      });
    }
  });
}
// watchEffect(() => {
//   if (projectDetail?.value?.indicatorData) {
//     const {
//       indicatorSystemId,
//       total: score,
//       indicators,
//     } = cloneDeep(projectDetail.value.indicatorData);
//     currentIndicatorSystem.value = indicatorSystemId;
//     total.value = score;
//     dataSource.value = indicators;
//   }
// });
const handleIndicatorSystemChange = (val: number) => {
  $loading?.start();
  getIndicatorSystemDetailById(val)
    .then((res) => {
      dataSource.value = res.indicators;
      // total.value = +res.weights || 0;
    })
    .catch(console.error)
    .finally(() => $loading?.stop());
};
// const appContext = getCurrentInstance()?.appContext;
// const handleIndicatorReplace = () => {
//   Modal.confirm({
//     icon: null,
//     title: "替换指标",
//     centered: true,
//     maskClosable: true,
//     closable: true,
//     content: () => createVNode(ReplaceModal, { projectDetail: {} }),
//     width: 900,
//     appContext,
//   });
// };
const handleSubmitClick = () => {
  if (currentIndicatorSystem.value === undefined) {
    message.error("请选择指标体系");
    return;
  }
  $loading?.start();
  saveProjectIndicatorSystem({
    projectId: parseFloat(route.params.id as string),
    systemId: currentIndicatorSystem.value,
    indicators: dataSource.value || [],
  })
    .then(() => {
      router.push({
        name: props.routeNamePrefix + "Projects",
      });
    })
    .catch(console.error)
    .finally(() => {
      $loading?.stop();
    });
};
const recommendButtonLoading = ref(false);
const handleRecommendClick = () => {
  if (!currentIndicatorSystem.value) return;
  recommendButtonLoading.value = true;
  getRecommendIndicatorSystem({
    indicatorSystemId: currentIndicatorSystem.value,
    projectId: parseFloat(route.params.id as string),
  })
    .then((res) => {
      recommendIndicators.value =
        res?.reduce<Record<string, any>>((obj, item) => {
          obj[item.indicatorId] = item;
          return obj;
        }, {}) || {};
    })
    .catch(console.error)
    .finally(() => {
      recommendButtonLoading.value = false;
    });
};
</script>
<style lang="scss" scoped>
.total-score {
  font-weight: bold;
}
.table {
  margin: 16px 0;
}
.recommend-button {
  margin-bottom: 16px;
}
.highlight {
  color: red;
  font-weight: bold;
  background-color: #ffe58f;
}
</style>
